package satir.analysis.analyst.factory;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import satir.analysis.analyst.Factor;
import satir.analysis.analyst.FactorAnalyst;
import satir.framework.refectoring.Factory;

/**
 * The Class FactorAnalyst, A factory for creating FactorAnalyst objects.
 * @version 3.0 April 2012
 * @author Creative Family
 */
public class FactorAnalystFactory implements Factory {

    /**
     * Create FactorAnalyst object.
     * @param json
     *         the JSON object
     * @return the FactorAnalyst object
     * @throws FactoryCreateInstantiationFailureException
     *           the FactoryCreateInstantiationFailureException
     */
    @Override
    public Object create(final JSONObject json)
	    throws FactoryCreateInstantiationFailureException {

	String key = "DECODE_ERROR";
	try {
	    key = json.getString("key");
	    String name = json.getString("name");
	    String description = json.getString("description");
	    ArrayList<Factor> factors = new ArrayList<Factor>();
	    // Factors builder
	    JSONArray array = json.getJSONArray("factors");
	    for (int i = 0; i < array.length(); i++) {
		JSONObject object = array.getJSONObject(i);
		factors.add(new Factor(object));
	    }
	    return new FactorAnalyst(key, name, description, factors);
	} catch (JSONException e) {
	    throw new FactoryCreateInstantiationFailureException(key, this);
	}
    }

}
